﻿using Learun.Util.SqlSugar;
using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-01-30 15:56
    /// 描 述：图纸目录
    /// </summary>
    public class ec_drawing_catalogueService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_drawing_catalogueEntity> _drawingCatalogueRepository => new Repository<ec_drawing_catalogueEntity>();
        Repository<ec_drawing_fileEntity> _drawingFileRepository => new Repository<ec_drawing_fileEntity>();
        Repository<ec_drawing_synEntity> _drawingSynRepository => new Repository<ec_drawing_synEntity>();
        Repository<ec_drawing_publishEntity> _drawingPublishRepository => new Repository<ec_drawing_publishEntity>();
        Repository<ec_operate_logEntity> _operateLogRepository => new Repository<ec_operate_logEntity>();
        #endregion
        #region 获取数据

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_drawing_catalogueEntity> GetList(string queryJson)
        {
            try
            {
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t.*,t2.F_RealName CreateUserName ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    strSql.Append("  FROM ec_drawing_catalogue t ");
                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    var ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($"  FROM ec_drawing_catalogue_{ProjectEntity.ProjectIndex} t ");
                }
                strSql.Append(@" LEFT JOIN lr_base_user t2 ON t.CreateUserID = t2.F_UserId ");
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["DrawingCatalogueName"].IsEmpty())
                {
                    dp.Add(new SugarParameter("DrawingCatalogueName", "%" + queryParam["DrawingCatalogueName"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t.DrawingCatalogueName LIKE @DrawingCatalogueName ");
                }
                if (!queryParam["FullPathContains"].IsEmpty())
                {
                    dp.Add(new SugarParameter("FullPathContains", "%" + queryParam["FullPathContains"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t.FullPath LIKE @FullPathContains ");
                }
                //图纸目录编辑页面选择上级目录时，排除本级和下级目录
                if (!queryParam["CurDrawingCatalogueID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("CurDrawingCatalogueID", queryParam["CurDrawingCatalogueID"].ToString(), DbType.String));
                    strSql.Append(" AND LOCATE(@CurDrawingCatalogueID, FullPath) = 0 ");
                }
                //查询包含图元图纸的目录
                if (!queryParam["EngineDataID"].IsEmpty())
                {
                    if (queryParam["ProjectId"].IsEmpty())
                    {
                        strSql.Append($@" AND t.DrawingCatalogueID IN (SELECT DrawingCatalogueID FROM ec_drawing_file_7 WHERE DrawingFileID IN (SELECT DrawingFileID FROM ec_enginedata_pixel_7 WHERE EngineDataID = '{queryParam["EngineDataID"].ToString()}')) ");
                    }
                    else
                    {
                        //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                        var ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                        strSql.Append($@" AND t.DrawingCatalogueID IN (SELECT DrawingCatalogueID FROM ec_drawing_file_{ProjectEntity.ProjectIndex} WHERE DrawingFileID IN (SELECT DrawingFileID FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{queryParam["EngineDataID"].ToString()}')) ");
                    }
                }
                if (!queryParam["UpDrawingCatalogueID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("UpDrawingCatalogueID", queryParam["UpDrawingCatalogueID"].ToString(), DbType.String));
                    strSql.Append(" AND t.UpDrawingCatalogueID = @UpDrawingCatalogueID ");
                }

                strSql.Append(" ORDER BY t.OrderID ");
                //return this.BaseRepository().FindList<ec_drawing_catalogueEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<ec_drawing_catalogueEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_drawing_catalogueEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    //return this.BaseRepository().FindEntity<ec_drawing_catalogueEntity>(keyValue);
                    return _drawingCatalogueRepository.GetById(keyValue);
                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@"SELECT * FROM ec_drawing_catalogue_{ ProjectEntity.ProjectIndex} WHERE DrawingCatalogueID = @DrawingCatalogueID ");
                    //List<ec_drawing_catalogueEntity> list = this.BaseRepository().FindList<ec_drawing_catalogueEntity>(strSql.ToString(), new { DrawingCatalogueID = keyValue }).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_drawing_catalogueEntity>(strSql.ToString(), new { DrawingCatalogueID = keyValue });
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            //var db = this.BaseRepository().BeginTrans();
            _drawingCatalogueRepository.AsTenant().BeginTran();
            try
            {
                //图纸目录删除时，删除子目录和目录下的图纸文件、图纸同步、图纸发布、操作日志数据。
                //获取所有要删除的图纸目录ID
                var listCatalogueID = GetList("{ ProjectId:\"" + ProjectId + "\",FullPathContains:\"" + keyValue + "\" }").Select(x => x.DrawingCatalogueID).Distinct().ToList();
                string strCatalogueIDs = string.Join(",", (from tb in listCatalogueID select tb).ToList());
                strCatalogueIDs = "'" + strCatalogueIDs + "'";
                //获取所有要删除的图纸文件ID
                var listFileID = new ec_drawing_fileBLL().GetList("{ ProjectId:\"" + ProjectId + "\",StrDrawingCatalogueIDs:\"" + strCatalogueIDs + "\" }").Select(x => x.DrawingFileID).Distinct().ToList();

                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    //执行删除操作
                    //db.Delete<ec_drawing_catalogueEntity>(t => listCatalogueID.Contains(t.DrawingCatalogueID));
                    _drawingCatalogueRepository.Delete(t => listCatalogueID.Contains(t.DrawingCatalogueID));
                    if (listFileID != null && listFileID.Count > 0)
                    {
                        //db.Delete<ec_drawing_fileEntity>(t => listFileID.Contains(t.DrawingFileID));
                        //db.Delete<ec_drawing_synEntity>(t => listFileID.Contains(t.DrawingFileID));
                        //db.Delete<ec_drawing_publishEntity>(t => listFileID.Contains(t.DrawingFileID));
                        //db.Delete<ec_operate_logEntity>(t => listFileID.Contains(t.OwnerID));
                        _drawingFileRepository.Delete(t => listFileID.Contains(t.DrawingFileID));
                        _drawingSynRepository.Delete(t => listFileID.Contains(t.DrawingFileID));
                        _drawingPublishRepository.Delete(t => listFileID.Contains(t.DrawingFileID));
                        _operateLogRepository.Delete(t => listFileID.Contains(t.OwnerID));
                    }
                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    string strFileIDs = string.Join(",", (from tb in listFileID select tb).ToList());
                    strFileIDs = "'" + strFileIDs + "'";
                    string delSqlParam = $" DELETE FROM ec_drawing_catalogue_{ ProjectEntity.ProjectIndex} WHERE FIND_IN_SET(DrawingCatalogueID,{strCatalogueIDs}); ";
                    if (!string.IsNullOrWhiteSpace(strFileIDs))
                    {
                        delSqlParam += $" DELETE FROM ec_drawing_file_{ ProjectEntity.ProjectIndex} WHERE FIND_IN_SET(DrawingFileID,{strFileIDs}); ";
                        delSqlParam += $" DELETE FROM ec_drawing_syn_{ ProjectEntity.ProjectIndex} WHERE FIND_IN_SET(DrawingFileID,{strFileIDs}); ";
                        delSqlParam += $" DELETE FROM ec_drawing_publish_{ ProjectEntity.ProjectIndex} WHERE FIND_IN_SET(DrawingFileID,{strFileIDs}); ";
                        delSqlParam += $" DELETE FROM ec_operate_log_{ ProjectEntity.ProjectIndex} WHERE FIND_IN_SET(OwnerID,{strFileIDs}); ";
                    }
                    //db.ExecuteBySql(delSqlParam);
                    SqlSugarHelper.Db.Ado.ExecuteCommand(delSqlParam);
                }
                //db.Commit();
                _drawingCatalogueRepository.AsTenant().CommitTran();
            }
            catch (Exception ex)
            {
                //db.Rollback();
                _drawingCatalogueRepository.AsTenant().RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_drawing_catalogueEntity entity, string ProjectId)
        {
            try
            {
                string fullPath = "";
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    GetFullPath(ref fullPath, entity.UpDrawingCatalogueID, entity.DrawingCatalogueID, ProjectId);
                    entity.FullPath = fullPath;
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        //this.BaseRepository().Update(entity);
                        _drawingCatalogueRepository.Update(entity);
                    }
                    else
                    {
                        //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_drawing_catalogue_{ ProjectEntity.ProjectIndex}", "DrawingCatalogueID");
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        _drawingCatalogueRepository.AsUpdateable(entity).AS($"ec_drawing_catalogue_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
                else
                {
                    entity.Create();
                    GetFullPath(ref fullPath, entity.UpDrawingCatalogueID, entity.DrawingCatalogueID, ProjectId);
                    entity.FullPath = fullPath;
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        //this.BaseRepository().Insert(entity);
                        _drawingCatalogueRepository.Insert(entity);
                    }
                    else
                    {
                        //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_drawing_catalogue_{ ProjectEntity.ProjectIndex}");
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        _drawingCatalogueRepository.AsInsertable(entity).AS($"ec_drawing_catalogue_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void InertEntity(ec_drawing_catalogueEntity entity, string ProjectId)
        {
            try
            {
                string fullPath = "";
                GetFullPath(ref fullPath, entity.UpDrawingCatalogueID, entity.DrawingCatalogueID, ProjectId);
                entity.FullPath = fullPath;
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    //this.BaseRepository().Insert(entity);
                    _drawingCatalogueRepository.Insert(entity);

                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    //this.BaseRepository().InsertByNoMap(entity, $"ec_drawing_catalogue_{ ProjectEntity.ProjectIndex}");
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    _drawingCatalogueRepository.AsInsertable(entity).AS($"ec_drawing_catalogue_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void EditEntity(ec_drawing_catalogueEntity entity, string ProjectId)
        {
            try
            {
                string fullPath = "";
                entity.Modify(entity.DrawingCatalogueID);
                GetFullPath(ref fullPath, entity.UpDrawingCatalogueID, entity.DrawingCatalogueID, ProjectId);
                entity.FullPath = fullPath;
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    //this.BaseRepository().Update(entity);
                    _drawingCatalogueRepository.Update(entity);

                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    //this.BaseRepository().UpdateByNoMap(entity, $"ec_drawing_catalogue_{ ProjectEntity.ProjectIndex}", "DrawingCatalogueID");
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    _drawingCatalogueRepository.AsUpdateable(entity).AS($"ec_drawing_catalogue_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 完整路径保存父级和子级的分类ID，用逗号分割
        /// </summary>
        /// <returns></returns>
        public void GetFullPath(ref string fullPath, string parentId, string id, string ProjectId)
        {
            if (string.IsNullOrEmpty(parentId) || parentId == "0")
            {
                fullPath = id;
            }
            else
            {
                var entity = GetEntity(parentId, ProjectId);
                fullPath = entity?.FullPath + "," + id;
            }
        }
        #endregion

    }
}
